"""
简历分析师智能体 - 专业的简历分析和评估
具备深度简历解析、技能匹配、经验评估等能力
"""

import asyncio
from typing import List, Dict, Any, Optional
import re
from datetime import datetime
import json

from ...core.interfaces import Task, TaskStatus
from ..base_agent import BaseAgent


class ResumeAnalyst(BaseAgent):
    """简历分析师智能体"""
    
    def __init__(self):
        super().__init__(
            name="resume_analyst",
            capabilities=[
                "resume_analysis",
                "skill_assessment", 
                "experience_evaluation",
                "education_analysis",
                "career_trajectory_analysis",
                "job_matching"
            ]
        )
        
        # 分析模板
        self.analysis_templates = {
            "comprehensive": """请对以下简历进行全面分析：

简历信息：{resume_content}

职位要求：{job_requirements}

请从以下维度进行详细分析：
1. 基本信息完整性
2. 工作经验匹配度
3. 技能符合程度  
4. 教育背景适配性
5. 职业发展轨迹
6. 优势和亮点
7. 不足和改进建议
8. 综合匹配评分（1-100分）

请提供具体的分析依据和建议。""",
            
            "skill_focused": """请专注分析简历中的技能匹配情况：

简历内容：{resume_content}
目标技能：{target_skills}

分析要点：
1. 技能覆盖率
2. 技能熟练程度
3. 技能组合合理性
4. 缺失的关键技能
5. 技能发展建议""",
            
            "experience_focused": """请重点分析工作经验：

简历内容：{resume_content}
目标岗位：{target_position}

分析内容：
1. 工作年限和稳定性
2. 相关经验匹配度
3. 职位层级进展
4. 行业背景符合度
5. 项目经验价值"""
        }
    
    async def _initialize_agent_specific(self):
        """初始化简历分析师特定功能"""
        # 这里可以初始化特定的分析工具或模型
        pass
    
    async def can_handle_task(self, task: Task) -> bool:
        """检查是否能处理任务"""
        resume_related_keywords = [
            "resume", "简历", "候选人", "candidate", "分析", "analysis",
            "技能", "skill", "经验", "experience", "匹配", "match"
        ]
        
        task_content = (task.description + " " + task.task_type).lower()
        
        return any(keyword in task_content for keyword in resume_related_keywords)
    
    async def _process_task_internal(self, task: Task) -> Dict[str, Any]:
        """处理简历分析任务"""
        try:
            task_type = task.task_type
            
            if task_type == "analyze_resume":
                return await self._analyze_single_resume(task)
            elif task_type == "analyze_multiple_candidates":
                return await self._analyze_multiple_candidates(task)
            elif task_type == "skill_assessment":
                return await self._assess_skills(task)
            elif task_type == "experience_evaluation":
                return await self._evaluate_experience(task)
            elif task_type == "generate_comprehensive_report":
                return await self._generate_comprehensive_report(task)
            elif task_type == "generate_comparison_report":
                return await self._generate_comparison_report(task)
            else:
                # 通用简历分析
                return await self._analyze_single_resume(task)
                
        except Exception as e:
            return {
                "error": str(e),
                "agent": self.name,
                "task_id": task.id
            }
    
    async def _analyze_single_resume(self, task: Task) -> Dict[str, Any]:
        """分析单个简历"""
        try:
            # 从任务描述中提取简历信息
            resume_query = self._extract_resume_query(task.description)
            
            # 使用RAG系统查询相关简历信息
            rag_result = await self.query_rag(
                query=resume_query,
                template_name="resume_analysis",
                top_k=5,
                return_intermediate=True
            )
            
            # 结构化分析
            structured_analysis = await self._perform_structured_analysis(
                rag_result, task.metadata
            )
            
            # 生成评分
            scoring = await self._calculate_resume_scores(structured_analysis)
            
            return {
                "analysis_type": "single_resume",
                "query": resume_query,
                "rag_result": rag_result,
                "structured_analysis": structured_analysis,
                "scoring": scoring,
                "recommendations": await self._generate_recommendations(structured_analysis),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "single_resume"}
    
    async def _analyze_multiple_candidates(self, task: Task) -> Dict[str, Any]:
        """分析多个候选人"""
        try:
            # 解析多个候选人查询
            candidates_info = self._extract_candidates_info(task.description)
            
            # 并行分析每个候选人
            analysis_tasks = []
            for candidate_info in candidates_info:
                sub_task = Task(
                    id=f"{task.id}_candidate_{len(analysis_tasks)}",
                    description=candidate_info.get("query", ""),
                    task_type="analyze_resume",
                    metadata=candidate_info
                )
                analysis_tasks.append(self._analyze_single_resume(sub_task))
            
            candidate_analyses = await asyncio.gather(*analysis_tasks, return_exceptions=True)
            
            # 整理结果
            successful_analyses = [
                analysis for analysis in candidate_analyses 
                if not isinstance(analysis, Exception) and "error" not in analysis
            ]
            
            return {
                "analysis_type": "multiple_candidates",
                "total_candidates": len(candidates_info),
                "successful_analyses": len(successful_analyses),
                "candidate_analyses": successful_analyses,
                "comparative_summary": await self._generate_comparative_summary(successful_analyses),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "multiple_candidates"}
    
    async def _assess_skills(self, task: Task) -> Dict[str, Any]:
        """技能评估"""
        try:
            skill_query = f"技能评估：{task.description}"
            
            # 查询技能相关信息
            rag_result = await self.query_rag(
                query=skill_query,
                template_name="general_qa",
                top_k=8
            )
            
            # 提取技能信息
            skills_analysis = await self._extract_skills_from_result(rag_result)
            
            # 技能匹配分析
            matching_analysis = await self._analyze_skill_matching(
                skills_analysis, task.metadata
            )
            
            return {
                "analysis_type": "skill_assessment",
                "query": skill_query,
                "skills_found": skills_analysis,
                "matching_analysis": matching_analysis,
                "skill_gaps": await self._identify_skill_gaps(matching_analysis),
                "skill_recommendations": await self._generate_skill_recommendations(matching_analysis),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "skill_assessment"}
    
    async def _evaluate_experience(self, task: Task) -> Dict[str, Any]:
        """经验评估"""
        try:
            experience_query = f"工作经验评估：{task.description}"
            
            rag_result = await self.query_rag(
                query=experience_query,
                template_name="general_qa",
                top_k=6
            )
            
            # 经验分析
            experience_analysis = await self._analyze_work_experience(rag_result)
            
            return {
                "analysis_type": "experience_evaluation",
                "query": experience_query,
                "experience_analysis": experience_analysis,
                "experience_scoring": await self._score_experience(experience_analysis),
                "career_progression": await self._analyze_career_progression(experience_analysis),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "experience_evaluation"}
    
    async def _generate_comprehensive_report(self, task: Task) -> Dict[str, Any]:
        """生成综合报告"""
        try:
            # 获取之前的分析结果
            previous_results = task.metadata.get("step_results", [])
            
            # 整合所有分析结果
            integrated_analysis = await self._integrate_analysis_results(previous_results)
            
            # 生成最终报告
            comprehensive_report = await self._create_comprehensive_report(
                task.description, integrated_analysis
            )
            
            return {
                "analysis_type": "comprehensive_report",
                "integrated_analysis": integrated_analysis,
                "comprehensive_report": comprehensive_report,
                "executive_summary": await self._create_executive_summary(comprehensive_report),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "comprehensive_report"}
    
    async def _generate_comparison_report(self, task: Task) -> Dict[str, Any]:
        """生成比较报告"""
        try:
            # 获取候选人分析结果
            candidate_analyses = task.metadata.get("candidate_analyses", [])
            
            if not candidate_analyses:
                return {"error": "No candidate analyses found for comparison"}
            
            # 生成比较分析
            comparison_result = await self._perform_candidate_comparison(candidate_analyses)
            
            # 生成排名和推荐
            ranking = await self._rank_candidates(candidate_analyses)
            
            return {
                "analysis_type": "comparison_report",
                "total_candidates": len(candidate_analyses),
                "comparison_analysis": comparison_result,
                "candidate_ranking": ranking,
                "hiring_recommendations": await self._generate_hiring_recommendations(ranking),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "analysis_type": "comparison_report"}
    
    def _extract_resume_query(self, description: str) -> str:
        """从任务描述中提取简历查询"""
        # 简单的关键词提取，实际应用中可以更复杂
        if "分析" in description and "简历" in description:
            return description
        else:
            return f"简历分析：{description}"
    
    def _extract_candidates_info(self, description: str) -> List[Dict[str, Any]]:
        """提取候选人信息"""
        # 简化实现，实际应用中需要更复杂的解析
        candidates = []
        
        # 尝试解析多个候选人信息
        if "候选人" in description or "candidate" in description.lower():
            # 假设描述中包含候选人信息
            parts = description.split("候选人")
            for i, part in enumerate(parts[1:], 1):  # 跳过第一个部分
                candidates.append({
                    "id": f"candidate_{i}",
                    "query": f"候选人{part.strip()}"
                })
        
        if not candidates:
            # 如果没有明确的候选人分割，创建一个通用查询
            candidates.append({
                "id": "candidate_1",
                "query": description
            })
        
        return candidates
    
    async def _perform_structured_analysis(
        self, 
        rag_result: Dict[str, Any], 
        metadata: Optional[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """执行结构化分析"""
        analysis = {
            "basic_info": await self._extract_basic_info(rag_result),
            "work_experience": await self._extract_work_experience(rag_result),
            "education": await self._extract_education(rag_result),
            "skills": await self._extract_skills_from_result(rag_result),
            "projects": await self._extract_projects(rag_result),
            "achievements": await self._extract_achievements(rag_result)
        }
        
        return analysis
    
    async def _extract_basic_info(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """提取基本信息"""
        answer = rag_result.get("answer", "")
        
        # 使用正则表达式提取基本信息
        basic_info = {
            "name": self._extract_with_regex(answer, r"姓名[：:]\s*([^\n,，]+)"),
            "email": self._extract_with_regex(answer, r"(\w+@\w+\.\w+)"),
            "phone": self._extract_with_regex(answer, r"(\d{11}|\d{3}-\d{4}-\d{4})"),
            "location": self._extract_with_regex(answer, r"地址[：:]\s*([^\n]+)")
        }
        
        return {k: v for k, v in basic_info.items() if v}
    
    async def _extract_work_experience(self, rag_result: Dict[str, Any]) -> List[Dict[str, Any]]:
        """提取工作经验"""
        answer = rag_result.get("answer", "")
        
        # 简化的工作经验提取
        experiences = []
        
        # 查找公司和职位信息
        company_pattern = r"([\u4e00-\u9fa5A-Za-z\s]+(?:公司|Corporation|Inc|Ltd|Co))"
        position_pattern = r"职位[：:]?\s*([^\n]+)"
        
        companies = re.findall(company_pattern, answer)
        positions = re.findall(position_pattern, answer)
        
        for i, company in enumerate(companies):
            experience = {
                "company": company.strip(),
                "position": positions[i].strip() if i < len(positions) else "未指定",
                "extracted_from": "rag_analysis"
            }
            experiences.append(experience)
        
        return experiences
    
    async def _extract_education(self, rag_result: Dict[str, Any]) -> List[Dict[str, Any]]:
        """提取教育背景"""
        answer = rag_result.get("answer", "")
        
        education = []
        
        # 查找学校和专业信息
        school_pattern = r"([\u4e00-\u9fa5A-Za-z\s]+(?:大学|学院|University|College))"
        major_pattern = r"专业[：:]?\s*([^\n]+)"
        
        schools = re.findall(school_pattern, answer)
        majors = re.findall(major_pattern, answer)
        
        for i, school in enumerate(schools):
            edu_item = {
                "school": school.strip(),
                "major": majors[i].strip() if i < len(majors) else "未指定",
                "extracted_from": "rag_analysis"
            }
            education.append(edu_item)
        
        return education
    
    async def _extract_skills_from_result(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """从结果中提取技能"""
        answer = rag_result.get("answer", "")
        
        # 技能关键词
        tech_skills = [
            "Python", "Java", "JavaScript", "C++", "React", "Vue", "Node.js",
            "Django", "Flask", "MySQL", "PostgreSQL", "MongoDB", "Redis",
            "Docker", "Kubernetes", "Git", "Linux", "AWS", "Azure"
        ]
        
        soft_skills = [
            "团队合作", "沟通能力", "领导力", "项目管理", "分析能力",
            "解决问题", "创新思维", "学习能力"
        ]
        
        found_tech_skills = [skill for skill in tech_skills if skill.lower() in answer.lower()]
        found_soft_skills = [skill for skill in soft_skills if skill in answer]
        
        return {
            "technical_skills": found_tech_skills,
            "soft_skills": found_soft_skills,
            "total_skills": len(found_tech_skills) + len(found_soft_skills)
        }
    
    async def _extract_projects(self, rag_result: Dict[str, Any]) -> List[Dict[str, Any]]:
        """提取项目经验"""
        answer = rag_result.get("answer", "")
        
        projects = []
        project_keywords = ["项目", "Project", "开发", "负责"]
        
        for keyword in project_keywords:
            if keyword in answer:
                # 简化的项目提取
                projects.append({
                    "description": f"涉及{keyword}相关工作",
                    "extracted_from": "keyword_matching"
                })
        
        return projects
    
    async def _extract_achievements(self, rag_result: Dict[str, Any]) -> List[str]:
        """提取成就和亮点"""
        answer = rag_result.get("answer", "")
        
        achievement_keywords = ["获得", "荣誉", "奖项", "证书", "认证", "专利"]
        achievements = []
        
        for keyword in achievement_keywords:
            if keyword in answer:
                achievements.append(f"具有{keyword}相关成就")
        
        return achievements
    
    def _extract_with_regex(self, text: str, pattern: str) -> Optional[str]:
        """使用正则表达式提取信息"""
        match = re.search(pattern, text)
        return match.group(1).strip() if match else None
    
    async def _calculate_resume_scores(self, analysis: Dict[str, Any]) -> Dict[str, float]:
        """计算简历评分"""
        scores = {
            "completeness": 0.0,
            "experience_relevance": 0.0,
            "skill_match": 0.0,
            "education_fit": 0.0,
            "overall": 0.0
        }
        
        # 完整性评分
        basic_info = analysis.get("basic_info", {})
        completeness_factors = len([v for v in basic_info.values() if v])
        scores["completeness"] = min(completeness_factors * 25, 100)
        
        # 技能匹配评分
        skills = analysis.get("skills", {})
        total_skills = skills.get("total_skills", 0)
        scores["skill_match"] = min(total_skills * 10, 100)
        
        # 经验相关性评分
        experience = analysis.get("work_experience", [])
        scores["experience_relevance"] = min(len(experience) * 30, 100)
        
        # 教育匹配评分
        education = analysis.get("education", [])
        scores["education_fit"] = min(len(education) * 50, 100)
        
        # 综合评分
        scores["overall"] = sum(scores.values()) / 4
        
        return scores
    
    async def _generate_recommendations(self, analysis: Dict[str, Any]) -> List[str]:
        """生成建议"""
        recommendations = []
        
        # 基于分析结果生成建议
        if not analysis.get("basic_info", {}).get("email"):
            recommendations.append("建议完善联系方式信息")
        
        skills = analysis.get("skills", {})
        if skills.get("total_skills", 0) < 5:
            recommendations.append("建议补充技能描述")
        
        if not analysis.get("projects"):
            recommendations.append("建议增加项目经验描述")
        
        if not recommendations:
            recommendations.append("简历信息较为完整，建议根据具体职位要求进行针对性优化")
        
        return recommendations
    
    async def _generate_comparative_summary(self, analyses: List[Dict[str, Any]]) -> Dict[str, Any]:
        """生成比较摘要"""
        if not analyses:
            return {"error": "No analyses to compare"}
        
        total_candidates = len(analyses)
        avg_scores = {}
        
        # 计算平均分数
        all_scores = [analysis.get("scoring", {}) for analysis in analyses]
        
        if all_scores:
            score_keys = set()
            for scores in all_scores:
                score_keys.update(scores.keys())
            
            for key in score_keys:
                scores_for_key = [scores.get(key, 0) for scores in all_scores if key in scores]
                avg_scores[key] = sum(scores_for_key) / len(scores_for_key) if scores_for_key else 0
        
        return {
            "total_candidates": total_candidates,
            "average_scores": avg_scores,
            "summary": f"共分析{total_candidates}名候选人，平均综合评分{avg_scores.get('overall', 0):.1f}分"
        }
    
    async def _integrate_analysis_results(self, step_results: List[Dict[str, Any]]) -> Dict[str, Any]:
        """整合分析结果"""
        integrated = {
            "resume_analysis": None,
            "entity_analysis": None,
            "additional_insights": []
        }
        
        for result in step_results:
            result_data = result.get("result", {})
            action = result.get("action", "")
            
            if "resume" in action.lower():
                integrated["resume_analysis"] = result_data
            elif "entity" in action.lower() or "kg" in action.lower():
                integrated["entity_analysis"] = result_data
            else:
                integrated["additional_insights"].append(result_data)
        
        return integrated
    
    async def _create_comprehensive_report(
        self, 
        original_query: str, 
        integrated_analysis: Dict[str, Any]
    ) -> str:
        """创建综合报告"""
        # 使用RAG生成综合报告
        report_query = f"""
        基于以下分析结果，生成详细的简历分析报告：
        
        原始查询：{original_query}
        
        分析结果：
        {json.dumps(integrated_analysis, ensure_ascii=False, indent=2)}
        
        请生成一份专业的简历分析报告，包括：
        1. 执行摘要
        2. 候选人基本情况
        3. 详细分析结果
        4. 优势和不足
        5. 推荐意见
        """
        
        rag_result = await self.query_rag(report_query, template_name="resume_analysis")
        return rag_result.get("answer", "报告生成失败")
    
    async def _create_executive_summary(self, comprehensive_report: str) -> str:
        """创建执行摘要"""
        # 提取报告的关键要点
        lines = comprehensive_report.split('\n')
        summary_lines = []
        
        for line in lines[:10]:  # 取前10行作为摘要
            if line.strip() and not line.startswith('#'):
                summary_lines.append(line.strip())
        
        return '\n'.join(summary_lines[:5])  # 最多5行摘要
    
    async def _perform_candidate_comparison(self, candidate_analyses: List[Dict[str, Any]]) -> Dict[str, Any]:
        """执行候选人比较"""
        comparison = {
            "criteria": ["overall_score", "skill_match", "experience_relevance"],
            "candidates": []
        }
        
        for i, analysis in enumerate(candidate_analyses):
            scoring = analysis.get("scoring", {})
            comparison["candidates"].append({
                "candidate_id": f"candidate_{i+1}",
                "scores": scoring,
                "rank": 0  # 将在排名中计算
            })
        
        return comparison
    
    async def _rank_candidates(self, candidate_analyses: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """对候选人进行排名"""
        candidates_with_scores = []
        
        for i, analysis in enumerate(candidate_analyses):
            scoring = analysis.get("scoring", {})
            overall_score = scoring.get("overall", 0)
            
            candidates_with_scores.append({
                "candidate_id": f"candidate_{i+1}",
                "overall_score": overall_score,
                "analysis": analysis
            })
        
        # 按综合分数排序
        candidates_with_scores.sort(key=lambda x: x["overall_score"], reverse=True)
        
        # 添加排名
        for rank, candidate in enumerate(candidates_with_scores, 1):
            candidate["rank"] = rank
        
        return candidates_with_scores
    
    async def _generate_hiring_recommendations(self, ranking: List[Dict[str, Any]]) -> Dict[str, Any]:
        """生成招聘推荐"""
        if not ranking:
            return {"recommendation": "无候选人数据"}
        
        top_candidate = ranking[0]
        
        recommendations = {
            "top_candidate": top_candidate["candidate_id"],
            "top_score": top_candidate["overall_score"],
            "recommendation": "",
            "next_steps": []
        }
        
        if top_candidate["overall_score"] >= 80:
            recommendations["recommendation"] = "强烈推荐，建议安排面试"
            recommendations["next_steps"] = ["安排技术面试", "进行背景调查", "薪资协商"]
        elif top_candidate["overall_score"] >= 60:
            recommendations["recommendation"] = "可以考虑，建议进一步评估"
            recommendations["next_steps"] = ["电话初步沟通", "补充信息收集"]
        else:
            recommendations["recommendation"] = "不建议进入下一轮"
            recommendations["next_steps"] = ["感谢信", "简历存档"]
        
        return recommendations
    
    async def _analyze_skill_matching(
        self, 
        skills_analysis: Dict[str, Any], 
        metadata: Optional[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """分析技能匹配"""
        target_skills = metadata.get("target_skills", []) if metadata else []
        
        found_skills = skills_analysis.get("technical_skills", [])
        
        matching = {
            "matched_skills": [],
            "missing_skills": [],
            "match_rate": 0.0
        }
        
        if target_skills:
            matching["matched_skills"] = [skill for skill in found_skills if skill.lower() in [t.lower() for t in target_skills]]
            matching["missing_skills"] = [skill for skill in target_skills if skill.lower() not in [f.lower() for f in found_skills]]
            matching["match_rate"] = len(matching["matched_skills"]) / len(target_skills) if target_skills else 0
        
        return matching
    
    async def _identify_skill_gaps(self, matching_analysis: Dict[str, Any]) -> List[str]:
        """识别技能差距"""
        return matching_analysis.get("missing_skills", [])
    
    async def _generate_skill_recommendations(self, matching_analysis: Dict[str, Any]) -> List[str]:
        """生成技能建议"""
        missing_skills = matching_analysis.get("missing_skills", [])
        recommendations = []
        
        for skill in missing_skills:
            recommendations.append(f"建议学习或补充{skill}技能")
        
        if not recommendations:
            recommendations.append("技能匹配良好，建议持续提升现有技能深度")
        
        return recommendations
    
    async def _analyze_work_experience(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析工作经验"""
        answer = rag_result.get("answer", "")
        
        analysis = {
            "total_experience_mentioned": self._count_experience_mentions(answer),
            "industries": self._extract_industries(answer),
            "company_types": self._extract_company_types(answer),
            "leadership_experience": self._detect_leadership_experience(answer)
        }
        
        return analysis
    
    def _count_experience_mentions(self, text: str) -> int:
        """统计经验提及次数"""
        experience_keywords = ["年经验", "工作", "任职", "负责", "参与"]
        count = 0
        for keyword in experience_keywords:
            count += text.count(keyword)
        return count
    
    def _extract_industries(self, text: str) -> List[str]:
        """提取行业信息"""
        industry_keywords = ["互联网", "金融", "教育", "医疗", "制造", "咨询", "科技"]
        found_industries = [industry for industry in industry_keywords if industry in text]
        return found_industries
    
    def _extract_company_types(self, text: str) -> List[str]:
        """提取公司类型"""
        company_types = ["初创", "上市", "外企", "国企", "民企"]
        found_types = [ctype for ctype in company_types if ctype in text]
        return found_types
    
    def _detect_leadership_experience(self, text: str) -> bool:
        """检测领导经验"""
        leadership_keywords = ["领导", "管理", "主管", "经理", "总监", "团队"]
        return any(keyword in text for keyword in leadership_keywords)
    
    async def _score_experience(self, experience_analysis: Dict[str, Any]) -> Dict[str, float]:
        """为经验评分"""
        scores = {
            "experience_depth": min(experience_analysis.get("total_experience_mentioned", 0) * 10, 100),
            "industry_diversity": min(len(experience_analysis.get("industries", [])) * 20, 100),
            "leadership_potential": 100 if experience_analysis.get("leadership_experience") else 0,
            "overall_experience": 0
        }
        
        scores["overall_experience"] = sum(scores.values()) / 3
        
        return scores
    
    async def _analyze_career_progression(self, experience_analysis: Dict[str, Any]) -> Dict[str, Any]:
        """分析职业发展"""
        return {
            "progression_indicators": experience_analysis.get("leadership_experience", False),
            "industry_focus": len(experience_analysis.get("industries", [])) <= 2,
            "growth_potential": "high" if experience_analysis.get("leadership_experience") else "medium"
        }